package com.dave.weixin.common.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * Created by Dave on 2018/7/12
 * Describes socket服务端通道
 */
public class ServerSocketChannelTest {

    ///////////////////////////////////////////////////////////////////////////
    // ServerSocketChannel是一个可以监听新进来的TCP连接的通道，就像标准IO中的ServerSocket
    ///////////////////////////////////////////////////////////////////////////


    public static void main(String[] args) throws IOException {

        //创建serverSocketChannel
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        //绑定监听端口
        socketChannel.socket().bind(new InetSocketAddress(8080));

        //监听新进来的连接
        while (true) {
            //accept()会一直阻塞直到有新的连接进来
            SocketChannel channel = socketChannel.accept();
        }


    }


    /**
     * 非阻塞模式的服务端socket
     *
     * @throws IOException
     */
    private static void noBlockingServerSocket() throws IOException {
        //创建serverSocketChannel
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        //绑定监听端口
        socketChannel.socket().bind(new InetSocketAddress(8080));

        socketChannel.configureBlocking(false);

        //监听新进来的连接
        while (true) {
            //在非阻塞模式下，accept（）方法会立刻返回，如果还没有新进来的连接，返回的将是null
            SocketChannel channel = socketChannel.accept();
            if (channel != null) {
                System.out.println("do something....");
            }
        }
    }


}
